package com.zzh.partnersys.controller;


import com.wf.captcha.SpecCaptcha;
import com.zzh.partnersys.chat.session.SessionFactory;
import com.zzh.partnersys.common.entity.response.LoginResponse;
import com.zzh.partnersys.common.exception.BusinessException;
import com.zzh.partnersys.common.exception.ResultCodeEnum;
import com.zzh.partnersys.common.exception.ResultUtils;
import com.zzh.partnersys.common.util.JwtUtil;
import com.zzh.partnersys.common.util.TokenUtils;
import com.zzh.partnersys.entity.UserDO;
import com.zzh.partnersys.entity.dto.UserTDO;
import com.zzh.partnersys.entity.request.*;
import com.zzh.partnersys.service.UserService;
import com.zzh.partnersys.utils.EmailRightUtils;
import com.zzh.partnersys.utils.PhoneRightUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.zzh.partnersys.constant.UserConstant.USER_LOGIN_STATE;


/**
 * <p>
 * 用户�?前端控制�?
 * </p>
 *
 * @author zzh
 * @since 2024-07-13
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;


    /**
     * 用户注册邮箱形式
     * @param userRegisterEmailRequest 请求参数
     * @return
     */
    @PostMapping("/register/toEmail")
    public ResultUtils<String> userRegisterEmail(@RequestBody UserRegisterEmailRequest userRegisterEmailRequest){
        if (userRegisterEmailRequest == null){
            return ResultUtils.fail("参数错误");
        }
        String userAccount = userRegisterEmailRequest.getUserAccount();//邮箱
        String userPassword = userRegisterEmailRequest.getUserPassword();//密码
        String checkPassword = userRegisterEmailRequest.getCheckPassword();//确认密码
        String code = userRegisterEmailRequest.getCode();//验证码
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,code)){//任意一个空都为true
            return ResultUtils.fail("参数错误");
        }
        //3.密码不少�?�?
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            return ResultUtils.fail("密码长度不能小于8位");
        }
        if (!userPassword.equals(checkPassword)){
            return ResultUtils.fail("密码不正确");
        }
        if(!EmailRightUtils.isRightEmail(userAccount)){
            return ResultUtils.fail("邮箱格式不正确");
        }
        //controller层倾向于对请求参数本身的校验，不涉及业务逻辑（越少越好）
        //service层是对业务逻辑的校验（有可能被controller之外的类调用�?
        //返回一个新账户
        String account = userService.userRegisterEmail(userAccount, userPassword, code);
        return ResultUtils.ok(account);
    }


    /**
     * 用户注册手机号形式
     * @param userRegisterPhoneRequest 请求参数
     * @return 返回账户
     */
    @PostMapping("/register/toPhone")
    public ResultUtils<String> userRegisterPhone(@RequestBody UserRegisterPhoneRequest userRegisterPhoneRequest){
        if (userRegisterPhoneRequest == null){
            return ResultUtils.fail("参数错误");
        }
        String userAccount = userRegisterPhoneRequest.getUserAccount();//邮箱
        String userPassword = userRegisterPhoneRequest.getUserPassword();//密码
        String checkPassword = userRegisterPhoneRequest.getCheckPassword();//确认密码
        String code = userRegisterPhoneRequest.getCode();//验证�?
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,code)){//任意一个空都为true
            return ResultUtils.fail("参数错误");
        }
        //3.密码不少�?�?
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            return ResultUtils.fail("密码长度不能小于8位");
        }
        if (!userPassword.equals(checkPassword)){
            return ResultUtils.fail("密码不正确");
        }
        if(!PhoneRightUtils.isRightPhone(userAccount)){
            return ResultUtils.fail("手机号格式不正确");
        }
        //controller层倾向于对请求参数本身的校验，不涉及业务逻辑（越少越好）
        //service层是对业务逻辑的校验（有可能被controller之外的类调用�?
        //返回一个新账户
        String account = userService.userRegisterPhone(userAccount, userPassword, code);
        return ResultUtils.ok(account);
    }


    /**
     * 邮箱形式登录
     * @param userLoginEmailRequest
     * @param request
     * @return
     */
    @PostMapping("/login/email")
    public ResultUtils<LoginResponse<UserDO>> userLoginEmail(@RequestBody UserLoginEmailRequest userLoginEmailRequest, HttpServletRequest request) {
        if (userLoginEmailRequest == null) {
            return null;
        }
        //检查参数
        String email = userLoginEmailRequest.getEmail();
        String code = userLoginEmailRequest.getCode();
        if (StringUtils.isAnyBlank(email,code)){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        if (!EmailRightUtils.isRightEmail(email)){
            throw new BusinessException("邮箱格式不正确",40000);
        }
        UserDO userDO = userService.userLoginEmail(email, code, request);
        
        // 生成 JWT Token
        String token = JwtUtil.createToken(userDO.getId());
        
        // 返回用户信息和 Token
        LoginResponse<UserDO> loginResponse =
            new LoginResponse<>(userDO, token);
        
        return ResultUtils.ok(loginResponse);
    }

    /**
     * 手机号形式登录
     * @param userLoginPhoneRequest 请求参数
     * @param request 请求对象
     * @return 返回账户
     */
    @PostMapping("/login/phone")
    public ResultUtils<com.zzh.partnersys.common.entity.response.LoginResponse<UserDO>> userLoginPhone(@RequestBody UserLoginPhoneRequest userLoginPhoneRequest, HttpServletRequest request) {
        if (userLoginPhoneRequest == null) {
            return null;
        }
        //检查参�?
        String phone = userLoginPhoneRequest.getPhone();
        String code = userLoginPhoneRequest.getCode();
        if (StringUtils.isAnyBlank(phone,code)){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        if (!PhoneRightUtils.isRightPhone(phone)){
            throw new BusinessException("手机号格式不正确",40000);
        }
        UserDO userDO = userService.userLoginPhone(phone, code, request);
        
        // 生成 JWT Token
        String token = JwtUtil.createToken(userDO.getId());
        
        // 返回用户信息和 Token
        LoginResponse<UserDO> loginResponse =
            new LoginResponse<>(userDO, token);
        
        return ResultUtils.ok(loginResponse);
    }


    /**
     * 用户登录——账户形式登录
     * @param userLoginAccountRequest
     * @param request
     * @return
     */
    @PostMapping("/login/account")
    public ResultUtils<com.zzh.partnersys.common.entity.response.LoginResponse<UserDO>> userLogin(@RequestBody UserLoginAccountRequest userLoginAccountRequest, HttpServletRequest request) {
        if (userLoginAccountRequest == null) {
            return null;
        }
        String userAccount = userLoginAccountRequest.getUserAccount();
        String userPassword = userLoginAccountRequest.getUserPassword();
//        String code = userLoginAccountRequest.getCode();
        //controller层倾向于对请求参数本身的校验，不涉及业务逻辑（越少越好）
        //service层是对业务逻辑的校验（有可能被controller之外的类调用�?
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        //登录检�?
        UserDO userDO = userService.userLoginAccount(userAccount, userPassword, request);
        
        // 生成 JWT Token
        String token = com.zzh.partnersys.common.util.JwtUtil.createToken(userDO.getId());
        
        // 返回用户信息和 Token
        LoginResponse<UserDO> loginResponse =
            new LoginResponse<>(userDO, token);
        
        return ResultUtils.ok(loginResponse);
    }


    /**
     * 获取登录验证码图片base
     * @return 验证码图片base64
     */
    @GetMapping("/login/captcha")
    public ResultUtils<Map<String, String>> getLoginCodeByCaptcha() {
        Map<String, String> resultMap = new HashMap<>();
        // 算术类型验证�?
        //ArithmeticCaptcha captcha = new ArithmeticCaptcha();
        //中文类型验证�?
        //ChineseCaptcha captcha = new ChineseCaptcha();
        // 英文与数字验证码
         SpecCaptcha captcha = new SpecCaptcha();
        //英文与数字动态验证码
        //GifCaptcha captcha = new GifCaptcha();
        //中文动态验证码
        //ChineseGifCaptcha captcha = new ChineseGifCaptcha();
        // N位运�? 默认两位，其他类型验证码时设置长�?
        captcha.setLen(5);
        // 获取计算的结�? 进行存储
        String result = captcha.text();
        String key = UUID.randomUUID().toString();
        // 对生成的key值进行MD5加密，MD5工具类应用，可自行处�?
        // 此处为redis工具类封装，设置key, value, key有效�?
        //我们还是采用前端校验，把code传过去（图片的code就没必要去放在redis了）
        //stringRedisTemplate.opsForValue().set(key, result, 70, TimeUnit.SECONDS);

        //返回前端
        resultMap.put("verifyCodeKey", key);
        resultMap.put("verifyCode", captcha.toBase64());
        resultMap.put("code", result);
        return ResultUtils.ok(resultMap);
    }


    /**
     * 获取推荐用户返回给前端
     * @return 推荐用户列表
     */
    @GetMapping("/recommend")
    public ResultUtils<List<UserDO>> getRecommendUserList(@RequestParam("limit") String limit,
                                            @RequestParam("pageSize") String pageSize,
                                            HttpServletRequest request){
        long limitLong = Long.parseLong(limit);
        long pageSizeLong = Long.parseLong(pageSize);
        List<UserDO> userDOList = userService.getRecommendUserList(limitLong,pageSizeLong,request);
        if (userDOList == null){
            throw new BusinessException(ResultCodeEnum.FAIL);
        }
        return ResultUtils.ok(userDOList);
    }


    /**
     * 随机匹配获取配对的用�?使用编辑距离算法)=>相似度越高排在越前面
     * @param num  要求返回多少用户
     * @return 匹配用户列表
     */
    @GetMapping("/match")
    public ResultUtils matchUserListDistance(@RequestParam long num,HttpServletRequest request){
        if(num < 0 || num > 20){
            throw new BusinessException("操作异常,数据量大",40000);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        //匹配
        List<UserDO> userDOList = userService.matchUserListDistance(num, currentUserDO);
        return ResultUtils.ok(userDOList);
    }


    /**
     * 获取当前用户
     * @param request 请求
     * @return  当前
     */
    @GetMapping("/current")
    public ResultUtils getCurrentUser(HttpServletRequest request){
        UserDO currentUserDO = userService.getCurrentUser(request);
        return ResultUtils.ok(currentUserDO);
    }

    //用户注册
    @PostMapping("/register")
    public ResultUtils userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
            return null;
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        //controller层倾向于对请求参数本身的校验，不涉及业务逻辑（越少越好）
        //service层是对业务逻辑的校验（有可能被controller之外的类调用�?
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)){
            return null;
        }
        long id = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.ok(id);

    }


    //查询用户
    @GetMapping("/search")
    public ResultUtils searchUsers(String username,HttpServletRequest request) {
        List<UserDO> userDOS = userService.searchUsers(username, request);
        return ResultUtils.ok(userDOS);
    }

    //删除用户
    @PostMapping("/delete")
    public ResultUtils deleteUser(@RequestBody long id,HttpServletRequest request) {
        //只允许管理员才可以删�?
        if (userService.isAdmin(request)){
            return ResultUtils.fail(null);
        }
        if (id <= 0) {
            return ResultUtils.fail(null);
        }
        boolean isDeleted = userService.removeById(id);
        if (isDeleted){
            return ResultUtils.ok(isDeleted);
        }else{
            return ResultUtils.fail(isDeleted);
        }
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public ResultUtils userLogout(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        boolean isLogout = userService.userLogout(request);
        if (isLogout){
            return ResultUtils.ok(isLogout);
        }else{
            return ResultUtils.fail(isLogout);
        }
    }

    @PutMapping("/updateUser")
    public ResultUtils<Boolean> updateUserInfo(@RequestBody UserTDO userTDO, HttpServletRequest request){
        //判断参数是否正确
        //从token中获取用户id
        Long currentUserIdOrThrow = TokenUtils.getCurrentUserIdOrThrow(request);
        UserDO userDO = userService.getCurrentUserById(currentUserIdOrThrow);

        //获取当前用户判断权限(管理员才可以修改当前用户才可以修改当前用户信息)
        boolean isUpdate = userService.updateUser(userTDO, userDO,request);
        return ResultUtils.ok(isUpdate);
    }



    /**
     * 获取用户信息(通过tags)
     * @param tagNameList
     * @return
     */
    @PostMapping("/getUsersByTags")
    public ResultUtils<List<UserDO>> userInfoListByTagsList(@RequestBody List<String> tagNameList){
        if (ObjectUtils.isEmpty(tagNameList)){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        System.out.println(tagNameList);
//        Gson gson = new Gson();
//        List<String> list = gson.fromJson(tagNameList, List.class);
        List<UserDO> userDOList = userService.searchUsersByTagsBySQL(tagNameList);
        return ResultUtils.ok(userDOList);
    }

    /**
     * 通过选中的tags去修改我们用户的标签信息 + 性别
     * @param updateRequest
     * @param request
     * @return
     */
    @PostMapping("/updateUserTags")
    public ResultUtils<List<UserDO>> updateUserTags(@RequestBody UserLoginUpdateRequest updateRequest, HttpServletRequest request){
        if (ObjectUtils.isEmpty(updateRequest)){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        List<String> tagNameList = updateRequest.getTagNameList();
        Integer gender = updateRequest.getGender();
        if (ObjectUtils.isEmpty(tagNameList)){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
//        System.out.println("tagNameList" + tagNameList);
//        System.out.println("gender" + gender);
        //更新用户tags信息
        userService.updateUserTagsAndGender(tagNameList,gender,request);
        return ResultUtils.ok(null);
    }


    /**
     * 根据当前用户id获取用户信息
     */
    @GetMapping("/selectUserById")
    public ResultUtils selectUserById(Long id){
        if (id == null || id <= 0){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        UserDO userDO = userService.selectUserById(id);
        if (userDO == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);//不存在id
        }
        return ResultUtils.ok(userDO);
    }

    /**
     * 根据当前用户账户查询获取用户信息
     */
    @GetMapping("/selectUserByAccount")
    public ResultUtils selectUserByAccount(String account){
        if (StringUtils.isBlank(account)){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        List<UserDO> userDOList = userService.selectUserByAccount(account);
        return ResultUtils.ok(userDOList);
    }

    /**
     * 根据一批用户id查询用户信息
     * @param idList
     * @return
     */
    @PostMapping("/selectUsersByIds")
    public ResultUtils selectUsersByIds(@RequestBody List<Long> idList){
        if (ObjectUtils.isEmpty(idList)){
            return ResultUtils.ok(null);
        }
        List<UserDO> userDOList = userService.selectUsersByIds(idList);
        return ResultUtils.ok(userDOList);
    }

    /**
     * 根据ID查询用户会员信息
     * @param id
     */
    @GetMapping("/selectUserMemberById")
    public ResultUtils selectUserMemberById(Long id){
        if (id == null || id <= 0){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        UserDO userMemberDO = userService.selectUserById(id);
        if (userMemberDO == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);//不存在id
        }
        Integer memberLevel = userMemberDO.getMemberLevel();
        return ResultUtils.ok(memberLevel);
    }

}

